package com.nsgf.library.ui.page.manager;

import static com.nsgf.library.photopicker.PhotoPicker.EXTRA_VIEW_ID;
import static com.nsgf.library.photopicker.PhotoPicker.KEY_SELECTED_PHOTOS;
import static com.nsgf.library.ui.page.manager.ManagerWorkOrderDetailsActivity.LOCAL_WORK_ORDER_FORM;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.WorkOrderDetailBean;
import com.nsgf.library.data.repository.DataRepository;
import com.nsgf.library.data.response.DataResult;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.ActivityNsgfManagerWorkOrderFormSubmitBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.matisse.Matisse;
import com.nsgf.library.photopicker.PhotoPicker;
import com.nsgf.library.photopicker.widget.PhotoAdapter;
import com.nsgf.library.ui.adapter.ManagerDamTaskListAdapter;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.skjz.utils.SPUtil;
import com.nsgf.skjz.utils.StringUtil;
import com.nsgf.skjz.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;

public class ManagerWorkOrderFromSubmitActivity extends BaseActivity {

    ManagerWorkOrderFromSubmitStates states;

    WorkOrderDetailBean workOrderDetailBean = new WorkOrderDetailBean();

    AccountRequester accountRequester;
    private ManagerDamTaskListAdapter mAdapter;
    // 创建Gson对象
    Gson gson = new Gson();

    @Override
    protected void initViewModel() {

        states = getActivityScopeViewModel(ManagerWorkOrderFromSubmitStates.class);
        accountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mAdapter = new ManagerDamTaskListAdapter(this);
        return new DataBindingConfig(R.layout.activity_nsgf_manager_work_order_form_submit, BR.vm, states)
                .addBindingParam(BR.click, new ClickProxy())
                .addBindingParam(BR.adapter, mAdapter);
    }

    private ActivityNsgfManagerWorkOrderFormSubmitBinding mBinding;

    private String orderCode = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = (ActivityNsgfManagerWorkOrderFormSubmitBinding) getBinding();

        orderCode = getIntent().getStringExtra("orderCode");
        getLifecycle().addObserver(accountRequester);

        states.titleBar.set(getIntent().getStringExtra("title"));
        String src = SPUtil.get(orderCode, LOCAL_WORK_ORDER_FORM, "", this);
        WorkOrderDetailBean.DataBean.PositionVOSBean bean = getIntent().getParcelableExtra("item");
        if (!StringUtil.isEmpty(src)) {
            workOrderDetailBean = gson.fromJson(src, WorkOrderDetailBean.class);

            /**
             * 回显巡查异常部位信息
             */
            if (null != workOrderDetailBean.getData().getAbnormalList()) {
                abnormalsTemporary.addAll(workOrderDetailBean.getData().getAbnormalList());
                for (int i = 0; i < workOrderDetailBean.getData().getAbnormalList().size(); i++) {

                    for (int j = 0; j < bean.getItems().size(); j++) {

                        if (bean.getItems().get(j).getPositionCode()
                                .concat(bean.getItems().get(j).getAreaCode())
                                .concat(bean.getItems().get(j).getItemCode())
                                .equals(workOrderDetailBean.getData().getAbnormalList().get(i).getPositionCode()
                                        .concat(workOrderDetailBean.getData().getAbnormalList().get(i).getAreaCode())
                                        .concat(workOrderDetailBean.getData().getAbnormalList().get(i).getItemCode()))) {

                            bean.getItems().get(j).setAbnormalDescribe(workOrderDetailBean.getData().getAbnormalList().get(i).getAbnormalDescribe());
                            bean.getItems().get(j).setLiveImageList(workOrderDetailBean.getData().getAbnormalList().get(i).getLiveImageList());
                            bean.getItems().get(j).setResultValue(workOrderDetailBean.getData().getAbnormalList().get(i).getResultValue());
                            if (!"txt".equals(bean.getItems().get(j).getResultType())) {
                                if (bean.getItems().get(j).getOptions().size() > 2) {
                                } else {
                                    bean.getItems().get(j).setCheck(true);
                                }
                                bean.getItems().get(j).setViewGone(View.VISIBLE);
                            }


                            /**
                             * 删除当前的巡查异常区域 带提交时重新存储
                             */
                            for (int k = 0; k < abnormalsTemporary.size(); k++) {
                                if (workOrderDetailBean.getData().getAbnormalList().get(i).getPositionCode()
                                        .concat(workOrderDetailBean.getData().getAbnormalList().get(i).getAreaCode())
                                        .concat(workOrderDetailBean.getData().getAbnormalList().get(i).getItemCode())
                                        .equals(abnormalsTemporary.get(k).getPositionCode()
                                                .concat(abnormalsTemporary.get(k).getAreaCode()
                                                        .concat(abnormalsTemporary.get(k).getItemCode())))) {

                                    abnormalsTemporary.remove(k);
                                    break;
                                }
                            }
                        }

                    }
                }
            }
            abnormals.addAll(abnormalsTemporary);
        }
        states.data.set(bean);
        mAdapter.notifyDataSetChanged();

    }

    public static class ManagerWorkOrderFromSubmitStates extends StateHolder {

        public final State<String> name = new State<>("");

        public final State<Boolean> loadingVisible = new State<>(false);
        public final State<WorkOrderDetailBean.DataBean.PositionVOSBean> data = new State<>(null);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (RESULT_OK == resultCode) {
            if (PhotoPicker.REQUEST_CODE == requestCode) {
                getController().displayLoading();
                int index = data.getIntExtra(EXTRA_VIEW_ID, 0);
                PhotoAdapter adapter = mAdapter.getPhotoAdapters().get(index);
//                adapter.setData(Matisse.obtainResult(data), Matisse.obtainPathResult(data));
                ArrayList<WorkOrderDetailBean.FileDto> photos = new ArrayList<>();
                ArrayList<WorkOrderDetailBean.FileDto> httpPhotos =
                        (ArrayList<WorkOrderDetailBean.FileDto>) data.getSerializableExtra(KEY_SELECTED_PHOTOS);
                if (null != httpPhotos) {
                    photos.addAll(httpPhotos);
                }
                for (String src : Matisse.obtainPathResult(data)) {
                    WorkOrderDetailBean.FileDto dto = new WorkOrderDetailBean.FileDto();
                    dto.setFilePath(src);
                    photos.add(dto);
                }
                adapter.refresh(photos);
                if (!adapter.getPhotoPaths().isEmpty()) {
                    getController().displayLoading();
                    List<WorkOrderDetailBean.FileDto> fileDto = new ArrayList<>();
                    for (WorkOrderDetailBean.FileDto path : adapter.getPhotoPaths()) {
                        if (path.getFilePath().startsWith("http")) {
                            fileDto.add(path);
                        } else {
                            DataRepository.getInstance().uploadFile(path.getFilePath())
                                    .subscribe(new io.reactivex
                                            .Observer<DataResult<ResponseStatus<WorkOrderDetailBean.FileDto>>>() {
                                        @Override
                                        public void onSubscribe(Disposable d) {
                                        }

                                        @Override
                                        public void onNext(DataResult<ResponseStatus<WorkOrderDetailBean.FileDto>> dataResult) {

                                            getController().dismissLoading();
                                            if (dataResult.getResponseStatus().isSuccess()) {

                                                if (200 == dataResult.getResult().getResponseCode()) {
                                                    fileDto.add(dataResult.getResult().getData());
                                                    if (adapter.getPhotoPaths().size() == fileDto.size()) {
                                                        getController().dismissLoading();
                                                        mAdapter.getCurrentList().get(index).setLiveImageList(fileDto);
                                                    }
                                                } else {

                                                    ToastUtils.showShortToast(dataResult.getResult().getMsg());
                                                }
                                            } else {
                                                getController().dismissLoading();
                                                ToastUtils.showShortToast(getErrorMsg(dataResult.getResponseStatus().getE()));
                                            }

                                        }

                                        @Override
                                        public void onError(Throwable e) {
                                            getController().dismissLoading();

                                        }

                                        @Override
                                        public void onComplete() {
                                            getController().dismissLoading();
                                        }
                                    });
                        }
                    }

                }
            }

        }

    }


    private List<WorkOrderDetailBean.DataBean.PtWorkOrderAbnormal> abnormals = new ArrayList<>();

    private List<WorkOrderDetailBean.DataBean.PtWorkOrderAbnormal> abnormalsTemporary = new ArrayList<>();//临时存储

    public class ClickProxy {

        public void submit() {

            abnormalsTemporary.clear();
            for (int i = 0; i < mAdapter.getCurrentList().size(); i++) {

                if ("txt".equals(mAdapter.getCurrentList().get(i).getResultType())) {

                    if (!StringUtil.isEmpty(((EditText) mAdapter.itemBindings.get(i)
                            .getView(R.id.et_nsgf_manager_abnormalDescribe)).getText().toString())) {

                        WorkOrderDetailBean.DataBean.PtWorkOrderAbnormal abnormal
                                = new WorkOrderDetailBean.DataBean.PtWorkOrderAbnormal();
                        abnormal.setAbnormalDescribe(((EditText) mAdapter.itemBindings.get(i)
                                .getView(R.id.et_nsgf_manager_abnormalDescribe)).getText().toString());
                        abnormal.setResultValue(((EditText) mAdapter.itemBindings.get(i)
                                .getView(R.id.et_nsgf_manager_abnormalDescribe)).getText().toString());
                        abnormal.setAreaCode(mAdapter.getCurrentList().get(i).getAreaCode());
                        abnormal.setAreaName(mAdapter.getCurrentList().get(i).getAreaName());
                        abnormal.setItemCode(mAdapter.getCurrentList().get(i).getItemCode());
                        abnormal.setPositionCode(mAdapter.getCurrentList().get(i).getPositionCode());
                        abnormal.setItemName(mAdapter.getCurrentList().get(i).getItemName());
                        abnormal.setPositionName(mAdapter.getCurrentList().get(i).getPositionName());
                        abnormal.setLiveImageList(mAdapter.getCurrentList().get(i).getLiveImageListSubmit());
                        abnormal.setResultType(mAdapter.getCurrentList().get(i).getResultType());
                        abnormalsTemporary.add(abnormal);
                    }

                } else if ("sel".equals(mAdapter.getCurrentList().get(i).getResultType())) {//三个选择 判刑是否为异常

                    if (mAdapter.getCurrentList().get(i).getOptions().size() > 2) {
                        if (!StringUtil.isEmpty(mAdapter.getCurrentList().get(i).getResultValue())) {
                            if (!mAdapter.getCurrentList().get(i).getValueSrc().
                                    equals(mAdapter.getCurrentList().get(i).getResultValue())) {

                                WorkOrderDetailBean.DataBean.PtWorkOrderAbnormal abnormal =
                                        new WorkOrderDetailBean.DataBean.PtWorkOrderAbnormal();
                                abnormal.setAbnormalDescribe(((EditText) mAdapter.itemBindings.get(i)
                                        .getView(R.id.et_nsgf_manager_abnormalDescribe)).getText().toString());
                                abnormal.setAreaCode(mAdapter.getCurrentList().get(i).getAreaCode());
                                abnormal.setAreaName(mAdapter.getCurrentList().get(i).getAreaName());
                                abnormal.setItemCode(mAdapter.getCurrentList().get(i).getItemCode());
                                abnormal.setItemName(mAdapter.getCurrentList().get(i).getItemName());
                                abnormal.setLiveImageList(mAdapter.getCurrentList().get(i).getLiveImageListSubmit());
                                abnormal.setPositionCode(mAdapter.getCurrentList().get(i).getPositionCode());
                                abnormal.setPositionName(mAdapter.getCurrentList().get(i).getPositionName());
                                abnormal.setResultType(mAdapter.getCurrentList().get(i).getResultType());
                                abnormal.setResultValue(mAdapter.getCurrentList().get(i).getResultValue());


                                abnormalsTemporary.add(abnormal);
                            }
                        }
                    } else {

                        /**
                         * 部位开关
                         */
                        if (mAdapter.getCurrentList().get(i).isCheck()) {

                            WorkOrderDetailBean.DataBean.PtWorkOrderAbnormal abnormal =
                                    new WorkOrderDetailBean.DataBean.PtWorkOrderAbnormal();

                            abnormal.setAbnormalDescribe(((EditText) mAdapter.itemBindings.get(i)
                                    .getView(R.id.et_nsgf_manager_abnormalDescribe)).getText().toString());
                            abnormal.setAreaCode(mAdapter.getCurrentList().get(i).getAreaCode());
                            abnormal.setAreaName(mAdapter.getCurrentList().get(i).getAreaName());
                            abnormal.setItemCode(mAdapter.getCurrentList().get(i).getItemCode());
                            abnormal.setItemName(mAdapter.getCurrentList().get(i).getItemName());
                            abnormal.setLiveImageList(mAdapter.getCurrentList().get(i).getLiveImageListSubmit());
                            abnormal.setPositionCode(mAdapter.getCurrentList().get(i).getPositionCode());
                            abnormal.setPositionName(mAdapter.getCurrentList().get(i).getPositionName());
                            abnormal.setResultType(mAdapter.getCurrentList().get(i).getResultType());
                            abnormal.setResultValue(mAdapter.getCurrentList().get(i).getResultValue());
                            abnormalsTemporary.add(abnormal);
                        }
                    }

                }


            }


            /**
             * 检验部位异常的内容是否填写完整
             */
            for (WorkOrderDetailBean.DataBean.PtWorkOrderAbnormal abnormal : abnormalsTemporary) {

                if ("sel".equals(abnormal.getResultType())) {
                    if (null == abnormal.getLiveImageList()) {
                        ToastUtils.showShortToast("请上传异常问题图片");
                        return;
                    } else if (StringUtil.isEmpty(abnormal.getAbnormalDescribe())) {
                        ToastUtils.showShortToast("请输入异常描述");
                        return;
                    }
                }

            }

            getController().displayLoading();
            //添加当前部位的异常内容
            abnormals.addAll(abnormalsTemporary);
            workOrderDetailBean.getData().setAbnormalList(abnormals);

            // 存入本地用于后期上传
            String json = gson.toJson(workOrderDetailBean);
            SPUtil.put(orderCode, LOCAL_WORK_ORDER_FORM, json, ManagerWorkOrderFromSubmitActivity.this);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(500);
                        Intent intent = new Intent();
                        intent.putExtra("position", getIntent().getIntExtra("position", 0));
                        setResult(RESULT_OK, intent);
                        finish();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }).start();
        }
    }

}
